<?php
/**
 * 定义 memcached 缓存类
 * @package cache
 */

/**
 * 使用 memcache 扩展来缓存数据
 * @package cache
 */
class memcached
{
    private static $instance = array();
    private $_conn;
    private static $dns = array();
    private $config = array();
    /**
     * 构造函数
     *
     */
    function __construct($server)
    {
        if (!extension_loaded('memcache')) {
            exception_handler('memcache 扩展未加载');
        }
        if(!self::$dns){
            self::$dns  = Core::getConfig('memcached');
        }
        $this->config = self::$dns[$server];
        if($this->config){
            $this->_conn = new Memcache();
            $this->_conn->connect($this->config['host'],$this->config['port']);
        }
    }

    public function __destruct() {
        if ($this->_conn) {
            $this->_conn->close();
        }
    }
    
    /*
     * 取得实例
     */
    public static function getInstance($server){
        if(empty(self::$instance[$server])) {
            self::$instance[$server] = new self($server);
        }
        return self::$instance[$server];
    }
    
    /**
     * 写入缓存
     *
     * @param string $id
     * @param mixed $data
     * @return boolean
     */
    function store($id, $data, $ttl=null, $compress=null)
    {
        $ttl = is_null($ttl)?$this->config['ttl']:$ttl;
        $compresse = is_null($compress)?$this->config['compress']:$compress;;
        return $this->_conn->set($id, $data, $compresse ? MEMCACHE_COMPRESSED : false, $ttl);
    }

    /**
     * 读取缓存，失败或缓存撒失效时返回 false
     *
     * @param string $id
     *
     * @return mixed
     */
    function fetch($id)
    {
        return $this->_conn->get($id);
    }

    /**
     * 删除指定的缓存
     *
     * @param string $id
     * @return boolean
     */
    function delete($id)
    {
        return $this->_conn->delete($id);
    }

    /**
     * 清除所有的缓存数据
     *
     * @return boolean
     */
    function clean()
    {
        return $this->_conn->flush();
    }
}

